import matplotlib.pyplot as plt
import numpy as np

#构造图像
img =  [[  0,  0,255,255,255,255,255,255],
        [  0,  0,255,  0,  0,  0,  0,255],
        [  0,  0,255,  0,255,255,  0,255],
        [255,255,255,  0,  0,  0,  0,255],
        [255,  0,  0,255,255,255,255,255],
        [255,  0,  0,255,  0,  0,  0,  0],
        [255,255,255,255,  0,  0,  0,  0]]
img = np.array(img)

# 算法
def img_fill(img, x,y):
    '''
        边界色：255
        填充色：180
    '''
    def fill(x,y):
        if img[x, y] != 180:
            img[x, y] = 180
    not_lines = lambda x,y:img[x,y] != 255
    is_empty = lambda x,y:(img[x,y] != 180 and
                           img[x,y] != 255)
    stack = [] # 栈
    stack.append((x,y)) # 当前像素入栈
    while stack:
        # 当前像素：
        pt = stack.pop()
        # x- 和 x+ 方向找到两个端点，并全部填充：
        x,y = pt; xl=xr = x
        while not_lines(xl, y):
            fill(xl, y)
            xl -= 1
        while not_lines(xr, y):
            fill(xr, y)
            xr += 1
        # y-1 和 y+1 线取每段x最大值入栈：
        for y in (y-1, y+1):
            x = xl # 扫描 xl到xr 之间像素
            while x <= xr:
                # 若存在非填充的一段
                if is_empty(x, y):
                    while is_empty(x+1, y):
                        x += 1 # 取其连续的最右一个
                    stack.append((x, y))
                x += 1 # 继续找是否有下一段
    return img

img = img_fill(img, 5,1)

# 保存图像
# plt.imsave("填充.png", img, cmap='gray_r')

# 显示图像
fig=plt.figure()
ax = fig.add_subplot(111)
ax.imshow(img, cmap='gray_r')
plt.show()